package com.pxmeta.app.controller.community;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pxmeta.circle.entity.CircleUserBanLog;
import com.pxmeta.circle.entity.UserCircle;
import com.pxmeta.circle.entity.dto.*;
import com.pxmeta.circle.entity.vo.CircleUserInfoVO;
import com.pxmeta.circle.entity.vo.SignInStatusVO;
import com.pxmeta.circle.service.ICircleUserBanLogService;
import com.pxmeta.circle.service.ICircleUserKickService;
import com.pxmeta.circle.service.IUserCircleService;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.enums.CircleUserLevelEnum;
import com.pxmeta.common.utils.AuthUtil;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.vo.CircleUserVO;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.user.service.IUserSignRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户圈子表 前端控制器
 * </p>
 *
 * @author wcl
 * @since 2022-05-14
 */
@RestController
@RequestMapping("/circle/userCircle")
@RequiredArgsConstructor
@Api(value = "圈子用户",tags = "圈子用户")
public class UserCircleController {


    private final IUserCircleService userCircleService;
    private final ICircleUserBanLogService circleUserBanLogService;
    private final IUserSignRecordService userSignRecordService;
    private final IUserService userService;

    @SaCheckLogin
    @ApiOperation(value = "获取圈子用户列表")
    @GetMapping("/getCircleUsers")
    public AjaxResult<List<CircleUserVO>> getCircleUsers(@RequestParam Long circleId,
                                                         @RequestParam Integer page,
                                                         @RequestParam Integer size,
                                                         @RequestParam(required = false) String name){
        List<CircleUserVO> users = userCircleService.getUserList(circleId, page, size, name);
        return AjaxResult.success(users);
    }

    @SaCheckLogin
    @ApiOperation("加入圈子")
    @PostMapping("/addUserCircle")
    public AjaxResult addUserCircle(@RequestBody UserCircleDTO dto) {
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        Long circleId = dto.getCircleId();
        UserCircle userCircle = new UserCircle();
        userCircle.setCircleId(circleId);
        userCircle.setUserId(userId);
        userCircle.setNickname(user.getNickname());
        userCircle.setSort(0);
        userCircleService.joinCircle(userCircle,dto.getIsInit());
        return AjaxResult.success("加入成功");
    }


    @SaCheckLogin
    @ApiOperation("批量加入圈子")
    @PostMapping("/batchAddUserCircle")
    public AjaxResult batchJoinCircle(@RequestBody BatchJoinCircleDTO dto) {
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        List<Long> circleIdList = dto.getCircleIdList();
        for (Long circleId : circleIdList) {
            UserCircle userCircle = new UserCircle();
            userCircle.setCircleId(circleId);
            userCircle.setUserId(userId);
            userCircle.setNickname(user.getNickname());
            userCircle.setSort(0);
            userCircleService.joinCircle(userCircle,dto.getIsInit());
        }

        return AjaxResult.success("加入成功");
    }

    @SaCheckLogin
    @ApiOperation("移交圈主身份")
    @PutMapping("/transferMaster")
    public AjaxResult transferMaster(@RequestBody TransferMasterDTO dto){
        Long userId = SecurityUtils.getUserId();
        StpUtil.checkRole(AuthUtil.getRole(dto.getCircleId(),CircleUserLevelEnum.CREATOR.getLevel()));
        userCircleService.transferMaster(userId, dto.getCircleId(), dto.getTargetUserId());
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("解除圈子")
    @DeleteMapping("/breakCircle")
    public AjaxResult breakCircle(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        StpUtil.checkRole(AuthUtil.getRole(circleId, CircleUserLevelEnum.CREATOR.getLevel()));
        userCircleService.breakCircle(circleId, userId);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("设置圈子管理员")
    @PostMapping("/addAdmin")
    public AjaxResult addAdmin(@RequestBody AddAdminDTO dto){

        Long ownerId = SecurityUtils.getUserId();
        Long circleId = dto.getCircleId();
        List<Long> adminUserIds = dto.getAdminUserIds();

        if (CollectionUtil.isNotEmpty(adminUserIds)
                &&adminUserIds.size()>2){
            return AjaxResult.error(HttpStatus.PARAMS_ERROR, "管理员添加数量上限！");
        }

        userCircleService.addAdmin(ownerId,circleId, adminUserIds);
        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation(value = "取消管理员")
    @DeleteMapping("/cancelAdmin")
    public AjaxResult cancelAdmin(@RequestParam Long circleId,
                                  @RequestParam Long adminUserId){
        Long ownerId = SecurityUtils.getUserId();
        userCircleService.cancelAdmin(circleId, ownerId, adminUserId);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation(value = "退出圈子")
    @DeleteMapping("/removeUserCircle")
    public AjaxResult<?> removeUserCircle(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        boolean remove = userCircleService.quit(userId, circleId);
        if (remove) {
            return AjaxResult.success();
        }
        return AjaxResult.error(HttpStatus.PARAMS_ERROR,"您不在这个圈子内，无法退出");

    }

    @SaCheckLogin
    @ApiOperation(value = "封禁圈子用户")
    @PostMapping("/banCircleUser")
    public AjaxResult<?> banCircleUser(@RequestBody BanUserDTO dto){
        Long userId = SecurityUtils.getUserId();
        CircleUserBanLog banUserLog = new CircleUserBanLog();
        banUserLog.setBanUserId(dto.getBanUserId());
        banUserLog.setReason(dto.getReason());
        banUserLog.setUserId(userId);
        banUserLog.setTime(dto.getTime());
        banUserLog.setCircleId(dto.getCircleId());
        banUserLog.setUnit(dto.getTimeUnit());
        circleUserBanLogService.save(banUserLog);
        return AjaxResult.success("操作成功");
    }


    @SaCheckLogin
    @ApiOperation("踢出圈子用户")
    @GetMapping("/kickCircleUser")
    public AjaxResult<?> kickCircleUser( KickUserDTO dto){
        Long userId = SecurityUtils.getUserId();
        userCircleService.kickUser(userId, dto);
        return AjaxResult.success("操作成功！");
    }


    @SaCheckLogin
    @ApiOperation("圈子签到")
    @PostMapping("/signIn")
    public AjaxResult signIn(@RequestBody SignInDTO dto){
        Long circleId = dto.getCircleId();
        Long userId = SecurityUtils.getUserId();
        userSignRecordService.signInCircle(circleId, userId);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("查询今日是否已经签到")
    @GetMapping("/getSignStatus")
    public AjaxResult getSignStatus(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        Boolean flag = userSignRecordService.getSignStatus(circleId, userId, 1);
        SignInStatusVO vo = SignInStatusVO.builder().signInStatus(flag).build();
        return AjaxResult.success(vo);
    }


    @SaCheckLogin
    @ApiOperation("获取用户在圈子里的资料")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        CircleUserInfoVO vo = userCircleService.getUserInfo(userId, circleId);
        return AjaxResult.success(vo);
    }

    @SaCheckLogin
    @ApiOperation("修改用户在圈子的昵称")
    @PutMapping("/updateNickname")
    public AjaxResult updateNickname(@RequestBody UserCircleDTO dto){

        Long circleId = dto.getCircleId();
        String nickname = dto.getNickname();

        if (StringUtils.isBlank(nickname)){
            return AjaxResult.error("昵称不能为空！");
        }
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<UserCircle> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserCircle::getCircleId, circleId)
                        .eq(UserCircle::getUserId,userId);
        UserCircle uc = userCircleService.getOne(wrapper);
        if (null == uc){
            return AjaxResult.error("数据不存在！");
        }

        uc.setNickname(nickname);
        userCircleService.updateById(uc);
        return AjaxResult.success();
    }

}
